﻿using System.Collections.Generic;
using UnityEditor.IMGUI.Controls;
using UnityEditor;
using UnityEngine;
using XFABManager;  

namespace XFGameFramework.Localization
{
#if UNITY_6000_2_OR_NEWER
    public class LanguageInfoTreeViewItem : TreeViewItem<int>
#else
    public class LanguageInfoTreeViewItem : TreeViewItem
#endif

    {
        public LanguageInfo languageInfo;

        public LanguageInfoTreeViewItem(LanguageInfo languageInfo) :  base(languageInfo.id, 0, string.Empty)
        {
            this.languageInfo = languageInfo;  
            UpdateDisplayName();
        }

        // 用于查询
        public void UpdateDisplayName() {
            displayName = string.Format("{0}{1}{2}{3}",
                languageInfo.id,
                languageInfo.type == MultiLanguageType.String ? languageInfo.str : string.Empty,
                languageInfo.type == MultiLanguageType.NetworkImage ? languageInfo.url : string.Empty,
                languageInfo.type == MultiLanguageType.Image ? string.Format("{0}{1}", languageInfo.image.projectName, languageInfo.image.imageName) : string.Empty);
        }

    }

#if UNITY_6000_2_OR_NEWER
    public class LanguageSearchListTree : TreeView<int>
#else
    public class LanguageSearchListTree : TreeView
#endif

    {

        private Dictionary<int, GUIContent> iconContents = new Dictionary<int, GUIContent>();

        private SerializedProperty id;

        private LanguageSearchWindow window;

        private MultiLanguageType multiLanguageType;

        private GUIStyle labelStyle;

        #region 重写方法

        internal static MultiColumnHeaderState CreateDefaultMultiColumnHeaderState()
        {
            return new MultiColumnHeaderState(GetColumns());
        }
        private static MultiColumnHeaderState.Column[] GetColumns()
        {
            var retVal = new MultiColumnHeaderState.Column[] {
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),  
            };
            retVal[0].headerContent = new GUIContent("ID", "语言配置唯一标识");
            retVal[0].minWidth = 50;
            retVal[0].width = 50;
            retVal[0].maxWidth = 1000;
            retVal[0].headerTextAlignment = TextAlignment.Left;
            retVal[0].canSort = false;
            retVal[0].autoResize = true;

            retVal[1].headerContent = new GUIContent("类型", "多语言配置类型");
            retVal[1].minWidth = 50;
            retVal[1].width = 50;
            retVal[1].maxWidth = 1000;
            retVal[1].headerTextAlignment = TextAlignment.Left;
            retVal[1].canSort = false;
            retVal[1].autoResize = true;
  
            retVal[2].headerContent = new GUIContent("值", "对应的数据");
            retVal[2].minWidth = 200;
            retVal[2].width = 500;
            retVal[2].maxWidth = 1000;
            retVal[2].headerTextAlignment = TextAlignment.Left;
            retVal[2].canSort = false;
            retVal[2].autoResize = true;
 

            return retVal;
        }

#if UNITY_6000_2_OR_NEWER
        protected override TreeViewItem<int> BuildRoot()
#else
        protected override TreeViewItem BuildRoot()
#endif

        {
            return CreateView();
        }
         
        protected override void RowGUI(RowGUIArgs args)
        {
            for (int i = 0; i < args.GetNumVisibleColumns(); ++i)
                CellGUI(args.GetCellRect(i), args.item as LanguageInfoTreeViewItem, args.GetColumn(i), ref args);
        }

        protected override void DoubleClickedItem(int id)
        { 
            this.id.intValue = id;
            this.id.serializedObject.ApplyModifiedProperties();
            
            
            this.window.Close();
        }

#if UNITY_6000_2_OR_NEWER 
        protected override IList<TreeViewItem<int>> BuildRows(TreeViewItem<int> root)
#else
        protected override IList<TreeViewItem> BuildRows(TreeViewItem root)
#endif

        {
            return base.BuildRows(root);
        }

        #endregion


        #region 方法
#if UNITY_6000_2_OR_NEWER
        public LanguageSearchListTree(TreeViewState<int> state, MultiColumnHeaderState mchs, SerializedProperty id, LanguageSearchWindow window, MultiLanguageType multiLanguageType) : base(state, new MultiColumnHeader(mchs))
#else
        public LanguageSearchListTree(TreeViewState state, MultiColumnHeaderState mchs, SerializedProperty id, LanguageSearchWindow window, MultiLanguageType multiLanguageType) : base(state, new MultiColumnHeader(mchs))

#endif

        {
            showBorder = true;
            showAlternatingRowBackgrounds = true;
            this.id = id;
            rowHeight = 20;
            this.window = window;
            this.multiLanguageType = multiLanguageType;
        }

        private void CellGUI(Rect cellRect, LanguageInfoTreeViewItem item, int column, ref RowGUIArgs args)
        {
            if (labelStyle == null) { 
                labelStyle = new GUIStyle(GUI.skin.label);
                labelStyle.richText = true;
                labelStyle.wordWrap = false;
            }

            switch (column)
            {
                case 0:

                    EditorGUI.LabelField(cellRect,item.languageInfo.id.ToString() , labelStyle);
                    break;
                case 1:
                    EditorGUI.LabelField(cellRect, item.languageInfo.type.ToString(), labelStyle);
                    break;

                case 2:

                    switch (item.languageInfo.type)
                    {
                        case MultiLanguageType.String:
                            EditorGUI.LabelField(cellRect, item.languageInfo.str , labelStyle);
                            break;
                        case MultiLanguageType.Image:

                            cellRect.width -= 20;

                            string projectName = item.languageInfo.image.projectName;
                            string imageName = item.languageInfo.image.imageName;

                            string message = string.Format("{0}/{1}", string.IsNullOrEmpty(projectName) ? "空" : projectName , string.IsNullOrEmpty( imageName) ? "空" : imageName);

                            GUI.Label(cellRect, message);

                            if (!iconContents.ContainsKey(item.languageInfo.id)) 
                            {
                                iconContents.Add(item.languageInfo.id, new GUIContent(EditorGUIUtility.IconContent("BuildSettings.Broadcom")));

                                Texture texture = LanguageConfigsInspector.GetImage(item.languageInfo.image.projectName, item.languageInfo.image.imageName);
                                 
                                if (texture != null)
                                    iconContents[item.languageInfo.id].image = texture;
                                else
                                    iconContents[item.languageInfo.id].tooltip = string.Format("图片{0}/{1}加载失败,请检查名称是否正确，或是否添加到资源模块?", item.languageInfo.image.projectName, item.languageInfo.image.imageName);
                            }

                            cellRect.x += cellRect.width;
                            cellRect.width = 20;
                            if (GUI.Button(cellRect, iconContents[item.languageInfo.id]))
                            {
                                ImageWindow window = EditorWindow.GetWindow<ImageWindow>();
                                window.SetTarget(iconContents[item.languageInfo.id].image);
                                window.Show();
                            }

                            break;
                        case MultiLanguageType.NetworkImage:
                            GUI.Label(cellRect, item.languageInfo.url);
                            break; 
                    }

                    break; 
            } 
        }


#if UNITY_6000_2_OR_NEWER
        private TreeViewItem<int> CreateView()
#else
        private TreeViewItem CreateView()
#endif
        {

#if UNITY_6000_2_OR_NEWER
            TreeViewItem<int> root = new TreeViewItem<int>(-1,-1);
#else 
            TreeViewItem root = new TreeViewItem(-1,-1);
#endif

            // AssetTreeItem

            // 编辑器模式 非运行状态  
            List<MultiLanguageConfigs> configs = MultiLanguageConfigsController.GetAllMultiLanguageConfigs();
             

            Dictionary<int, LanguageInfo> languageInfos = new Dictionary<int, LanguageInfo>();

            foreach (var item in configs)
            {
                LanguageConfig languageConfig = item.GetLanguageConfigData(window.language);
                if(languageConfig == null) continue;
                foreach (var info in languageConfig.languagesInfo)
                {
                    if (!languageInfos.ContainsKey(info.id)) 
                        languageInfos.Add(info.id, info); 
                }
            }

            foreach (var item in languageInfos.Values)
            {
                if (multiLanguageType == MultiLanguageType.String)
                {
                    if (item.type == MultiLanguageType.String)
                    {
                        LanguageInfoTreeViewItem languageInfoTreeViewItem = new LanguageInfoTreeViewItem(item);
                        root.AddChild(languageInfoTreeViewItem);
                    }
                }
                else 
                {
                    if (item.type == MultiLanguageType.Image || item.type == MultiLanguageType.NetworkImage)
                    {
                        LanguageInfoTreeViewItem languageInfoTreeViewItem = new LanguageInfoTreeViewItem(item);
                        root.AddChild(languageInfoTreeViewItem);
                    }
                }
            }
            
            return root;
        }

#endregion
    }

}


